Welcome to the Java Tutorials. The objective of these tutorials is to provide in depth understand of java from basic questions like what is java tutorial, core java, where it is used, what type of applications are created in java and why use java.
In addition to free Java Tutorials, you can find interview questions, how to tutorials and issues and their resolutions of Java.
Java is a programming language that was created by James Gosling from Sun Microsystems (Sun) in 1991 and first made publicly available in 1995, after Sun Microsystems was inherited by Oracle. The platform was originally designed for interactive television, but it surpassed the technology and design of the digital cable television industry at the time. Today, Java remains an open-source programming language that falls under the GPL (General Public License) The language derives much of its syntax from C and C++, but lacks the power of those languages because it asks less of the user (less customization, more simplicity). For example, tasks such as garbage collection (the process of reducing memory being used by the program) are automated in Java. Five principles were used in the creation of the Java programming language:
Java was built as an exclusively object-oriented programming language—which doesn’t mean much right now, but will later in this guide. For now, suffice it to say that object-oriented programming allows for the creation of efficient, organized, and powerful code. Simply put, Java is a multithreaded, object-oriented, platform-independent programming language. This means that Java programs can perform multiple tasks using object-oriented concepts that can work across all platforms and operating systems. It is the most important factor distinguishing Java from other languages. Java helps us to develop normal desktop applications, mobile applications, and web applications using separate packages such as the J2ME package for mobile application development and the J2EE package for web application development. In this guide, we are going to learn the basics of object-oriented concepts as they apply to Java programming. We have two different types of application development concepts in Java: console-based application and GUI application development. Let’s see how to develop these types of applications using Java.
Java is a programming language that is supported by all devices, whether it is an Android phone, a Windows computer, or an Apple product. Java’s flexibility has made it one of the most popular programming languages around the globe. Java can be used to create web applications, games, Windows applications, database systems, Android apps, and much more. Java’s combined simplicity and power makes it different from other programming languages. Java is simple in that it doesn’t expect too much from the user in terms of memory management or dealing with a vast and complex hive of intricate classes extending from each other. Although this doesn’t make much sense right now, it will once we start learning about inheritance in Java. A Java program is run through a Java Virtual Machine (JVM), which is essentially a software implementation of an operating system that is used to execute Java programs. The compiler (process of converting code into readable instructions for the computer) analyzes the Java code and converts it into byte code, which then allows the computer to understand the instructions issued by the programmer and execute them in the appropriate manner. The distribution of the Java platform comes in two packages: the Java Runtime Environment (JRE) and the Java Development Kit (JDK). The JRE is essentially the Java Virtual Machine (JVM) that runs Java programs. The JDK, on the other hand, is a fully featured software development kit that includes the JRE, compilers, tools, etc. A casual user who only wants to run Java programs on their machine would only need to install the JRE, as it contains the JVM that allows Java programs to be executed. However, a Java programmer must download the JDK. We will explore these concepts in greater detail in the next part. As previously stated, Java programming creates an object-oriented and platform-independent program because the Java compiler creates a .class file instead of an .exe file. This .class file is an intermediate file that has byte code, and this is the reason why Java programs are platform independent. However, there are also disadvantages: Java programs take more time to complete their execution because the .class file must first load in the JVM before they are able to run in the OS. We can develop all kinds of applications using Java, but we need to use separate packages for separate application developments. For example, if you want develop a desktop application, then you need to use JDK; if you want to develop an Android application, then you need to use Android SDK, because they have different sets of classes.
We will now use this sample code as an example to start the Java learning process. This code should make it easy to understand the basic structure of a Java program.
import java.util.Scanner; public class ThisIsAClass { public static void main (String args[]) { int x = 5; System.out.println(x); } }
The first line import java.util.Scanner; it is using the special keyword import, which allows the programmer to import tools in the Java library that aren’t included by default when starting a new class. After the keyword import, the programmer specifies a specific directory within the Java library for the Scanner tool by typing out: java.util.Scanner, which first accesses the Java library in the Utilities directory before accessing the specific tool needed, which in this case is “Scanner.” By default, when starting a Java class, only the bare minimum tools and functions from the Java library that are needed for any basic program will be provided. For example, you don’t need to import packages for a simple program. If the programmer wants to use more than just the basic functionalities, they must use the “Import” keyword to give themselves more tools to work with. You will also start to notice that there is a semicolon “;” after each statement. This semicolon functions as a period does for an English sentence. When the compiler is going through the program to prepare it for its execution, it will check for semicolons, so it knows where a specific statement ends and a new one starts. The next thing you’ll notice in the sample code is: public class ThisIsAClass. There are three elements to this line that are very important to understand. public—Defines the scope of the class and whether or not other classes have access to the class. This may not make sense now, but you will gain a better understanding of what this means when we learn about “Inheritance and Polymorphism.” class—A class can be thought of as a “section” of code. For example:
Section {everything here is the content of the section}
Again, you will gain a better understanding of how classes can be useful when we learn about Inheritance and Polymorphism. ThisIsAClass—This third and final element of this important line is “ThisIsAClass,” which is simply a custom name that the user can define. You can call this anything, as all it does is give the “Section” or “Class” a name.
Section: Name { Essay/Contents } In code, it would be presented: Class ThisIsAClass { Code }
Another thing you may be scratching your head over are the curly braces: “{” and “}.” All that these characters do is tell the compiler where a specific section starts and ends. In English, this could be thought of as starting a sentence with a capital letter or indenting a new paragraph. One thing to note is that the spacing in code does not affect whether or not it works. However, it is conventional and efficient to write properly spaced code so that you and other programmers can read and understand it more easily. You will learn how to space as you read more sample code. Eventually, you will start to notice trends in how conventional spacing works in programming.
public static void main (String args[]) { int x = 5; System.out.println(“The number is” + x); } }
As shown in the above sample code, two curly braces are set in bold to indicate that they communicate with each other. Whatever is written between them is the “Section” or “Class” of name “ThisIsAClass.” The sample applies to the bold and underlined curly braces to indicate that they are separate section dividers for the section within the parent section. The parent section is again considered a class, whereas the section within the parent section is considered a sub-section, or a subclass, or the formal term, a method. A method is essentially a subclass that also has its own special elements, similar to a class but more specific. This contains four elements: a scope (public/private/protected), a return type, a name, and parameters. The scope, return type, and parameters are things you will understand better when we learn about Methods, along with Inheritance and Polymorphism.
This method is a special method because it is named “main” and so it will be the first method that is called. The compiler always looks for the method named “main” at the process start. The main method must hold the following properties: “public static void” and have “String args[]” as the argument in the parameters. There can only be one main method in a Java project. The idea of the main method is that it will be the first method to be called, and so you can think of it as the home base for calling other methods and traveling to other classes (you will learn what this means later). For the remainder of this guide, your program must be written within this main method, as it is a special method that the compiler will always be looking for. The contents of this method will also be introduced when learning about “Variables” later on in this guide. For now, this brief explanation should be enough for you to understand what is going on: int x = 5;—A variable is being declared (a container) that is a type of integer (whole number), and it holds the value of five. The “=” is used to assign values to variables. System.out.println—This is a classic line that every beginner learns; all it does is print a line of text to the console. Example The console is where the program’s output is placed in order for the programmer to test his or her program. The “System.out.println” line contains parenthesis and a string of text within those parentheses. The string of text must be surrounded by quotation marks in order for the program to know that it has to print out text instead of an actual variable like “x.” The reason the user can’t just say: “System.out.println(“The number is: x”);” is because the program won’t know if x is a variable or not. The program reads anything within quotation marks as a piece of text instead of a container holding a value. Therefore, the x must be outside of the quotation marks. Then again, you can’t say System.out.println(“The number is: ” x ); because the program needs a specific keyword to know that the piece of text and the variable are two entities that need to be joined or “concatenated” together. The “+” symbol is used to show that the string of text and the variable “x” are to be connected together; this will allow the program to output “The number is: 5” (without the quotation marks). That is why the line is: “System.out.println(“The number is: ” + x );” Commenting: Commenting is the final fundamental concept to understand in a programming language. Although it is not necessary, it can greatly help you and other programmers around you if you ever forget how the program works. This concept is used by programmers as an opportunity to explain their code using common English. A compiler will always ignore comments, as they aren’t actual code. They are simply explanations that were written to help people understand what was programmed. In order to write a comment, you must use “//” or “/*” and “*/.” The “//” symbol is used to comment on one line. For example, if you were to explain what a certain variable was going to be used for, you would do the following:
int x = 5; // this variable is going to be used to find the total money
The compiler will ignore the commented line, but will process int x = 5. However, you can’t use the “//” symbol with the following:
int x = 5; // this variable is going to be used to find the total money
This is because the “//” symbol is only used for one line, and the comment is on two lines. You could do:
int x = 5; // this variable is going to be used to find the total money
As long as the comment is one line, it is fine. Anything on the line after that symbol is considered a comment. The other technique does the same thing as “//” except it supports multi-line commenting. You must start the comment with “/*” and end it with “*/.” Example:
int x = 5; /* this variable is going to be used to find the total money */
A variable is essentially a storage unit that holds a certain type of data. It is named by the programmer and used to identify the data it stores. A variable can usually be accessed or changed at any time. You can write information to it, take information from it, and even copy the information to store in another variable.
In Java, a variable has a specific type that determines what size it is and the layout of its memory. The Java language defines three types of variables.
Instance variables are declared within a class but accessed outside of any method, constructor, or block. Instance variables are created with the keyword “new” and are destroyed when the object is destroyed. An instance variable is visible to all methods, constructors, and blocks within the class where it is declared. By giving a variable the keyword “public,” it can be accessed by subclasses within the class. However, it is recommended to set a variable’s access modifier to “private” when possible. All instance variables have a default value, unlike local variables, which do not have default values. Example:
public class Test { public int num; // integer named num public void dog() { num = 3; } }
In this example, we declare the integer “num” outside of any method, and can easily access it within any method that is inside of the class “Test.”
Static variables are declared outside of any method, constructor, or block, and are declared with the keyword “static.” If a variable is static, only one instance of that variable will exist, regardless of how many instances of the object are called. Static variables are rarely used except for constant values, which are variables that never change. Example:
public class Test { public static final int num = 3; // integer named num public void dog() { System.out.println(num); } }
In this example, we declare an int called “num” and it set to be public, static, and final. This means that it can be accessed from within subclasses, only one instance of it can ever exist, and the value can never be changed.
Local variables are only declared within methods, blocks, or constructors. They are only created when the method, block, or constructor is created, and then they are destroyed as soon as the method ends. You can only access local variables within the method, block, or constructor where it is called; they are not visible outside of where they are called. Local variables do not have a default value. Example: public void cat(){ // method named cat int x = 0; // int with value of 0 } In this example, a variable named “x” is called within the method “cat.” That variable only exists within the context of cat, and it cannot be directly called or accessed outside of that method.
Variables are used to store data. Java has multiple built-in data types that are used to store predefined types of data. These data types are called primitive data types, and are the most basic data types in the Java programming language. You can also create your own data types, which we will go over later. Java has eight primitive data types.
The byte data type is an 8-bit signed two’s complement integer. It has a default value of zero when it is declared, a maximum value of 127, and a minimum value of -128. A byte is useful when you want to save memory space, especially in large arrays. Example
byte b = 1; // has a value of one
The short data type is a 16-bit signed two’s complement integer. Its maximum range is 32,767 and its minimum value is -32,768. A short is used to save memory or to clarify your code. Example:
short s = 1; // has a value of one
The int data type is a 32-bit signed two’s complement integer. Its maximum value is 2,147,483,647 (231 -1) and its minimum value is -2,147,483,648 (-231). Int is the most commonly used data type for integral numbers, unless memory is a concern. Example:
int i = 1; // has a value of one
The long data type is a 64-bit signed two’s complement integer. Its maximum value is 9,223,372,036,854,775,807 (263 -1) and its minimum value is -9,223,372,036,854,775,808 (-263). This data type is used when a larger number is required than would be possible with an int. Example:
long l = 1; // has a value of one
The floating point data type is a double-precision 64-bit IEEE 754 floating point. The min and max range is too large to discuss here. A float is never used when precision is necessary, such as when dealing with currency. Example:
float f = 1200.5f; //value of one thousand two hundred, and a half
The double point data type is a double-precision 64-bit IEEE 754 floating point. It is often the data type of choice for decimal numbers. The min and max range is too large to discuss here. A float is never used when precision is necessary, such as when dealing with currency. Example:
double d = 1200.5d; // value of one thousand two hundred, and a half
A boolean data type represents one bit of data. It can contain two values: true or false. It is used for simple flags to track true or false conditions. Example:
boolean b = true; // has a value of true
The char data type is a single 16-bit Unicode character. Its minimum value is “/u0000” (or 0) and its maximum value is “/uffff” (or 65,535 inclusive) Example:
char c = 'w'; // returns the letter "w"
Another commonly used data type is called String. String is not a primitive data type, but it is a very commonly used data type that stores collection of characters or text. Example:
String cat = "meow"; // sets value of cat to "meow"
This example gets a String named “cat” and sets it to the string of characters that spell out “meow.”
The declaration of a variable has three parts: the data type, variable name, and the stored value. Note that there is a specific convention and set of rules that are used when naming variables. A variable name can be any length of Unicode letters and numbers, but it must start with a letter, the dollar sign “$,” or an underscore “_,” or else it will return a syntax error. It is also common naming convention to start the name with a lowercase letter, followed by each subsequent word starting with a capital letter. For example, in the variable named “theName,” the first word “the” starts with a lowercase letter, and each following word, in this case “Name,” starts with a capital letter. Example:
int theName = 123; // value of 123
In the example above, the data type is int and the name of the variable is the Name. The value stored inside that variable is 123. You can also declare a variable without storing a value in it. Example:
int name; // no value
You can do this if you choose to declare it later.
After a variable is declared, then you can read its value or change it. After the variable has been initially declared, you can only reference it by its name; you only need to declare its data type when you are declaring the variable. Example:
name = 2; // sets the int "name" to a value of 2
The example above sets the value of name to 2. Notice how I never restated the data type. Example:
System.out.println(name); // prints the value of name to the console
This example reads the value of “name” and writes it to the console. Variables can also be added together for example. Example:
int a; // no value int b = 1; // value of one int c = 2; // value of two a = b + c; // sets a to the value of b + c
In the example above, we set the value of a to equal the value of b and c added together. The addition sign is known as an operator, which we are going to learn about in the following section. It is also possible to a certain extent to combine values of variables that are different data types. Example:
int a; // no value float b = 1; // value of one int c = 2; // value of two a = (int) (b + c); // sets the int "name" to a value of b + c
This example is just like the one before, except we have changed the data type of b from int to float. The only difference when adding them together is that we had to include something called a “cast” in the equation. What a cast does is simply let the compiler know that the value of (b + c) should be of the data type int. Note that for this example, if the value of b + c were to equal a decimal number (for example 3.2), the value of a would not be 3.2 but rather 3, because int does not support decimals.
Using what we have learned about variables, we can now create a simple calculator to add numbers together for us. The first thing we will want to do is declare three variables: one to store the value, one to represent the first number we want to add, and one to represent the second number we want to add. We will declare these variables as double so that we can add decimal numbers: double a = 0; // stores value of addition double b = 3.55; // first number to add double c = 52.6; // second number to add Next, we will simply set the value of a to equal the value of b and c combined, and then print out the value of a. a = b + c; System.out.println(a); If you run this program, it will print out 56.15. Now you have created a very simple calculator. I highly encourage you to play around with this and test things for yourself. Change the data type of the variables, add more numbers together, and experiment to understand how things work. Our design of course tutorials and interview questions is practical and informative. At TekSlate, we offer resources to help you learn various IT courses. We avail both written material and demo video tutorials. For in-depth knowledge and practical experience explore Online Java Training.
You liked the article?
Like: 0
Vote for difficulty
Current difficulty (Avg): Medium
TekSlate is the best online training provider in delivering world-class IT skills to individuals and corporates from all parts of the globe. We are proven experts in accumulating every need of an IT skills upgrade aspirant and have delivered excellent services. We aim to bring you all the essentials to learn and master new technologies in the market with our articles, blogs, and videos. Build your career success with us, enhancing most in-demand skills in the market.